package org.jeecg.modules.xxgx.fpgl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.common.util.LoginUserUtil;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.xxgx.common.enums.TdyslxDmEnum;
import org.jeecg.modules.xxgx.djgl.entity.CsXxFpxxCezs;
import org.jeecg.modules.xxgx.djgl.entity.tdyw.*;
import org.jeecg.modules.xxgx.djgl.enums.ZsfsEnum;
import org.jeecg.modules.xxgx.djgl.service.ICsXxFpxxCezsService;
import org.jeecg.modules.xxgx.fjys.vo.FjysVO;
import org.jeecg.modules.xxgx.fpgl.entity.CsXxFpxx;
import org.jeecg.modules.xxgx.fpgl.entity.CsXxFpxxExt;
import org.jeecg.modules.xxgx.fpgl.entity.CsXxFpxxmx;
import org.jeecg.modules.xxgx.fpgl.service.ICsXxFpxxExtService;
import org.jeecg.modules.xxgx.fpgl.service.ICsXxFpxxService;
import org.jeecg.modules.xxgx.fpgl.service.ICsXxFpxxmxService;
import org.jeecg.modules.xxgx.fpgl.vo.CsXxFpxxPage;
import org.jeecg.modules.xxgx.fpgl.vo.CsXxFpxxVO;
import org.jeecg.modules.xxgx.fpgl.vo.EditDybzParam;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;


/**
 * @Description: 销项发票
 * @Author: jeecg-boot
 * @Date:   2023-09-21
 * @Version: V1.0
 */
@Api(tags="销项发票")
@RestController
@RequestMapping("/xxgx/fpgl/csXxFpxx")
@Slf4j
public class CsXxFpxxController {
	@Autowired
	private ICsXxFpxxService csXxFpxxService;
	@Autowired
	private ICsXxFpxxmxService csXxFpxxmxService;
	@Autowired
	private ICsXxFpxxExtService csXxFpxxExtService;
	@Autowired
	private ICsXxFpxxCezsService csXxFpxxCezsService;

	/**
	 * 分页列表查询
	 *
	 * @param csXxFpxx
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "销项发票-分页列表查询")
	@ApiOperation(value="销项发票-分页列表查询", notes="销项发票-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="tax/xxgl/fpkjtz/fpcgl/FpcList")
	public Result<IPage<CsXxFpxx>> queryPageList(CsXxFpxx csXxFpxx,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		csXxFpxx.setCompanyId(LoginUserUtil.getQyxxByLoginUser().getId());
		QueryWrapper<CsXxFpxx> queryWrapper = QueryGenerator.initQueryWrapper(csXxFpxx, req.getParameterMap());
		Page<CsXxFpxx> page = new Page<CsXxFpxx>(pageNo, pageSize);
		IPage<CsXxFpxx> pageList = csXxFpxxService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@ApiOperation(value="销项发票-合计统计", notes="销项发票-合计统计")
	@GetMapping(value = "/countHj")
	@PermissionData(pageComponent="tax/xxgl/fpkjtz/fpcgl/FpcList")
	public Result<Map> countHj(CsXxFpxx csXxFpxx,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		csXxFpxx.setCompanyId(LoginUserUtil.getQyxxByLoginUser().getId());
		QueryWrapper<CsXxFpxx> queryWrapper = QueryGenerator.initQueryWrapper(csXxFpxx, req.getParameterMap());
		List<CsXxFpxx> list = csXxFpxxService.list(queryWrapper);
		BigDecimal jshjhj = list.stream().map(CsXxFpxx::getJshj).reduce(BigDecimal.ZERO, BigDecimal::add);
		BigDecimal jehj = list.stream().map(CsXxFpxx::getHjje).reduce(BigDecimal.ZERO, BigDecimal::add);
		BigDecimal sehj = list.stream().map(CsXxFpxx::getHjse).reduce(BigDecimal.ZERO, BigDecimal::add);
		Map returnMap = new HashMap();
		returnMap.put("jshjhj",jshjhj);
		returnMap.put("jehj",jehj);
		returnMap.put("sehj",sehj);
		return Result.OK(returnMap);
	}

	/**
	 *   添加
	 *
	 * @param csXxFpxxPage
	 * @return
	 */
	@AutoLog(value = "销项发票-添加")
	@ApiOperation(value="销项发票-添加", notes="销项发票-添加")
    @RequiresPermissions("xxgx.fpgl:cs_xx_fpxx:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CsXxFpxxPage csXxFpxxPage) {
		CsXxFpxx csXxFpxx = new CsXxFpxx();
		BeanUtils.copyProperties(csXxFpxxPage, csXxFpxx);
		csXxFpxxService.saveMain(csXxFpxx, csXxFpxxPage.getCsXxFpxxmxList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param csXxFpxxPage
	 * @return
	 */
	@AutoLog(value = "销项发票-编辑")
	@ApiOperation(value="销项发票-编辑", notes="销项发票-编辑")
    @RequiresPermissions("xxgx.fpgl:cs_xx_fpxx:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CsXxFpxxPage csXxFpxxPage) {
		CsXxFpxx csXxFpxx = new CsXxFpxx();
		BeanUtils.copyProperties(csXxFpxxPage, csXxFpxx);
		CsXxFpxx csXxFpxxEntity = csXxFpxxService.getById(csXxFpxx.getId());
		if(csXxFpxxEntity==null) {
			return Result.error("未找到对应数据");
		}
		csXxFpxxService.updateMain(csXxFpxx, csXxFpxxPage.getCsXxFpxxmxList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "销项发票-通过id删除")
	@ApiOperation(value="销项发票-通过id删除", notes="销项发票-通过id删除")
    @RequiresPermissions("xxgx.fpgl:cs_xx_fpxx:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		csXxFpxxService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "销项发票-批量删除")
	@ApiOperation(value="销项发票-批量删除", notes="销项发票-批量删除")
    @RequiresPermissions("xxgx.fpgl:cs_xx_fpxx:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.csXxFpxxService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "销项发票-通过id查询")
	@ApiOperation(value="销项发票-通过id查询", notes="销项发票-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CsXxFpxxVO> queryById(@RequestParam(name="id",required=true) String id) {
		CsXxFpxx csXxFpxx = csXxFpxxService.getById(id);
		if(csXxFpxx==null) {
			return Result.error("未找到对应数据");
		}
		CsXxFpxxVO csXxFpxxVO = new CsXxFpxxVO();
		BeanUtils.copyProperties(csXxFpxx,csXxFpxxVO);

		CsXxFpxxExt csXxFpxxExt = csXxFpxxExtService.getById(csXxFpxx.getId());
		if(csXxFpxxExt != null) {
			if(TdyslxDmEnum.JZFW.getValue().equals(csXxFpxx.getTdyslxdm())){
				csXxFpxxVO.setTdywJzfw(JSON.parseObject(csXxFpxxExt.getTdywInfo(), Jzfw.class));
			} else if(TdyslxDmEnum.HWYSFW.getValue().equals(csXxFpxx.getTdyslxdm())){
				csXxFpxxVO.setTdywHwysfwList(JSONArray.parseArray(csXxFpxxExt.getTdywInfo(), Hwysfwmx.class));
			} else if(TdyslxDmEnum.BDCXS.getValue().equals(csXxFpxx.getTdyslxdm())){
				csXxFpxxVO.setTdywBdcxs(JSON.parseObject(csXxFpxxExt.getTdywInfo(), Bdcxsfw.class));
			} else if(TdyslxDmEnum.BDCJYZLFW.getValue().equals(csXxFpxx.getTdyslxdm())){
				csXxFpxxVO.setTdywBdcjyzlfw(JSON.parseObject(csXxFpxxExt.getTdywInfo(), Bdcjyzlfw.class));
			} else if(TdyslxDmEnum.LKYSFW.getValue().equals(csXxFpxx.getTdyslxdm())){
				csXxFpxxVO.setTdywLkysfwList(JSONArray.parseArray(csXxFpxxExt.getTdywInfo(), Lkysfwmx.class));
			}

			//取附加要素
			String fjysJson = csXxFpxxExt.getFjysInfo();
			if(!StringUtils.isEmpty(fjysJson)) {
				csXxFpxxVO.setFjysList(JSONArray.parseArray(fjysJson, FjysVO.class));
			}
		}

		//取差额征收
		if(!ZsfsEnum.PTZS.getValue().equals(csXxFpxx.getZsfs())) {
			List<CsXxFpxxCezs> cezsList = csXxFpxxCezsService.lambdaQuery().eq(CsXxFpxxCezs::getFromid, csXxFpxx.getId()).list();
			csXxFpxxVO.setCezsList(cezsList);
		}

		return Result.OK(csXxFpxxVO);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "销项发票明细通过主表ID查询")
	@ApiOperation(value="销项发票明细主表ID查询", notes="销项发票明细-通主表ID查询")
	@GetMapping(value = "/queryCsXxFpxxmxByMainId")
	public Result<List<CsXxFpxxmx>> queryCsXxFpxxmxListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CsXxFpxxmx> csXxFpxxmxList = csXxFpxxmxService.selectByMainId(id);
		return Result.OK(csXxFpxxmxList);
	}

	 @AutoLog(value = "销项发票-修改打印标记")
	 @ApiOperation(value="销项发票-修改打印标记", notes="销项发票-修改打印标记")
	 @PostMapping(value = "/editDybz")
	 public Result editDybz(@RequestBody @Valid EditDybzParam editDybzParam) {
		 return csXxFpxxService.updateDybz(editDybzParam);
	 }

	 @ApiOperation(value="销项发票-发票导出", notes="销项发票-发票导出")
	 //@RequiresPermissions("xxgx.fpgl:cs_xx_fpxx:exportXlsMain")
	 @RequestMapping(value = "/exportXlsMain")
	 public ModelAndView exportXlsMain(HttpServletRequest request, CsXxFpxx csXxFpxx) {
		 csXxFpxx.setCompanyId(LoginUserUtil.getQyxxByLoginUser().getId());//当前登录用户所属企业
		 // Step.1 组装查询条件查询数据
		 QueryWrapper<CsXxFpxx> queryWrapper = QueryGenerator.initQueryWrapper(csXxFpxx, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 //配置选中数据查询条件
		 String selections = request.getParameter("selections");
		 if(oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 queryWrapper.in("id",selectionList);
		 }
		 //Step.2 获取导出数据
		 List<CsXxFpxx> csXxFpxxList = csXxFpxxService.list(queryWrapper);

		 // Step.3 组装pageList
		 List<CsXxFpxxPage> pageList = new ArrayList<CsXxFpxxPage>();
		 for (CsXxFpxx main : csXxFpxxList) {
			 CsXxFpxxPage vo = new CsXxFpxxPage();
			 BeanUtils.copyProperties(main, vo);
			 List<CsXxFpxxmx> csXxFpxxmxList = csXxFpxxmxService.selectByMainId(main.getId());
			 vo.setCsXxFpxxmxList(csXxFpxxmxList);
			 pageList.add(vo);
		 }

		 // Step.4 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "销项发票列表");
		 mv.addObject(NormalExcelConstants.CLASS, CsXxFpxxPage.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("销项发票数据", "导出人:"+sysUser.getRealname(), "销项发票"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		 return mv;
	 }
    /**
    * 导出excel
    *
    * @param request
    * @param csXxFpxx
    */
	@ApiOperation(value="销项发票-明细导出", notes="销项发票-明细导出")
    //@RequiresPermissions("xxgx.fpgl:cs_xx_fpxx:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CsXxFpxx csXxFpxx) {
		csXxFpxx.setCompanyId(LoginUserUtil.getQyxxByLoginUser().getId());//当前登录用户所属企业
      // Step.1 组装查询条件查询数据
      QueryWrapper<CsXxFpxx> queryWrapper = QueryGenerator.initQueryWrapper(csXxFpxx, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<CsXxFpxx> csXxFpxxList = csXxFpxxService.list(queryWrapper);

      // Step.3 组装pageList
      List<CsXxFpxxPage> pageList = new ArrayList<CsXxFpxxPage>();
      for (CsXxFpxx main : csXxFpxxList) {
          CsXxFpxxPage vo = new CsXxFpxxPage();
          BeanUtils.copyProperties(main, vo);
          List<CsXxFpxxmx> csXxFpxxmxList = csXxFpxxmxService.selectByMainId(main.getId());
          vo.setCsXxFpxxmxList(csXxFpxxmxList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "销项发票列表");
      mv.addObject(NormalExcelConstants.CLASS, CsXxFpxxPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("销项发票数据", "导出人:"+sysUser.getRealname(), "销项发票"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("xxgx.fpgl:cs_xx_fpxx:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CsXxFpxxPage> list = ExcelImportUtil.importExcel(file.getInputStream(), CsXxFpxxPage.class, params);
              for (CsXxFpxxPage page : list) {
                  CsXxFpxx po = new CsXxFpxx();
                  BeanUtils.copyProperties(page, po);
                  csXxFpxxService.saveMain(po, page.getCsXxFpxxmxList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 @AutoLog(value = "销项发票-取开票员")
	 @ApiOperation(value="销项发票-取开票员", notes="销项发票-取开票员")
	 @PostMapping(value = "/loadUser")
	 public Result<List<SysUser>> loadUser() {
		 List<SysUser> userListByLoginUser = LoginUserUtil.getUserListByLoginUser();
		 return Result.OK(userListByLoginUser);
	 }
}
